from django.db import models
from django.contrib.auth.hashers import make_password, check_password
from utils.custom_jwt import generate_jwt_token, checkout_token
from apps.users import constants


# 定义老师模型类
class Teacher(models.Model):
    username = models.CharField(max_length=20, unique=True, verbose_name='用户名')
    password = models.CharField(max_length=128, verbose_name='登录密码')
    nickname = models.CharField(max_length=20, unique=True, verbose_name='老师昵称')
    name = models.CharField(max_length=20, null=True, blank=True, verbose_name='老师姓名')
    telephone = models.CharField(max_length=20, null=True, blank=True, verbose_name='电话')
    email = models.CharField(max_length=20, null=True, blank=True, verbose_name='邮箱')
    job = models.CharField(max_length=20, default="待分配", verbose_name='老师职能')
    avatar = models.ImageField(upload_to='avatar/', null=True, blank=True, verbose_name='用户头像')
    is_staff = models.BooleanField(default=False, verbose_name='是否为管理员')
    is_superuser = models.BooleanField(default=False, verbose_name='是否为超级管理员')
    is_active = models.BooleanField(default=True, verbose_name='是否激活')
    remark = models.CharField(max_length=50, null=True, blank=True, verbose_name='老师信息备注')

    class Meta:
        # 指明数据库表名
        db_table = 'tb_teacher'
        # 在admin站点中显示的名称
        verbose_name = '老师表'
        # 显示的复数名称
        verbose_name_plural = verbose_name

    def __str__(self):
        """定义每个数据对象的显示信息"""
        return self.username

    # 对用户输入密码进行加密存储
    def set_password(self, raw_password):
        self.password = make_password(raw_password)

    def check_password(self, raw_password):
        return check_password(raw_password, self.password)

    def generate_user_token(self, expire_second=constants.TOKEN_EXPIRES):
        return generate_jwt_token({
            "id": self.id,
            "username": self.username,
        }, expire_second)

    @classmethod
    def checkout_user_by_token(cls, token):
        payload = checkout_token(token)
        if not payload:
            return None
        user_id = payload.get('id')
        user = cls.objects.filter(id=user_id).first()
        return user

